import java.util.Arrays;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class RadixSort {
    public static void main(String[] args) {
        // 如果是8千万的数据所需要的内存最少需要3.3G
        // 80000000*11*4/1024/1024/1024 => 3.3G
        int[] arr = new int[8000000];
        for (int i = 0; i < 8000000; i++) {
            arr[i] = (int) (Math.random() * 80000);
        }

        //System.out.println(Arrays.toString(shellSort(arr)));
        long start = System.currentTimeMillis();

        radixSort(arr);
        long end = System.currentTimeMillis();
        System.out.println(end - start);  //1199  ,交换法800万个随机数据的数组需要的ms数
    }

    public static void radixSort(int[] arr) {
        int[][] bucket = new int[10][arr.length];
        int[] bucketCount = new int[10];  //计算每个桶有多少个数的指针

        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        int maxLength = (max + "").length();

        int index = 0;
        for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
            for (int j = 0; j < arr.length; j++) {
                int digitOfElement = arr[j] / n % 10;  //获取指定的位数
                bucket[digitOfElement][bucketCount[digitOfElement]] = arr[j];
                bucketCount[digitOfElement]++;
            }
            for (int k = 0; k < bucketCount.length; k++) {
                if (bucketCount[k] != 0) {
                    for (int l = 0; l < bucketCount[k]; l++) {
                        arr[index++] = bucket[k][l];
                    }
                }
                bucketCount[k] = 0;
            }
            index = 0;
            //System.out.println("第"+(i+1)+"次排序后"+Arrays.toString(arr));
        }


    }
}
